import json
import os
import time
from datetime import datetime, timedelta
import requests
from django.conf import settings

class TokenManager:
    def __init__(self):
        self.token_file = os.path.join(settings.BASE_DIR, 'ebay', 'token.json')
        self.token_data = self._load_token()
        self.client_id = settings.EBAY_CLIENT_ID
        self.client_secret = settings.EBAY_CLIENT_SECRET
        
        # 根据环境选择API URL
        if getattr(settings, 'EBAY_SANDBOX', True):  # 默认使用沙箱环境
            self.oauth_url = "https://api.sandbox.ebay.com/identity/v1/oauth2/token"
            self.api_url = "https://api.sandbox.ebay.com"
        else:
            self.oauth_url = "https://api.ebay.com/identity/v1/oauth2/token"
            self.api_url = "https://api.ebay.com"
            
        self.scopes = [
            "https://api.ebay.com/oauth/api_scope"
        ]

    def _load_token(self):
        """从文件加载令牌数据"""
        if os.path.exists(self.token_file):
            try:
                with open(self.token_file, 'r') as f:
                    return json.load(f)
            except (json.JSONDecodeError, IOError) as e:
                print(f"Error loading token file: {e}")
                return None
        return None

    def _save_token(self, token_data):
        """保存令牌数据到文件"""
        try:
            new_token_data= {
                "access_token": token_data,
                "expires_in": 7200,
                "token_type": "Application Access Token",
                "expires_at": 1749618123
            }
            with open(self.token_file, 'w') as f:
                json.dump(new_token_data, f, indent=4)
            self.token_data = token_data
            setattr(settings, 'EBAY_AUTH_TOKEN',  token_data)
        except IOError as e:
            print(f"Error saving token file: {e}")

    def get_token(self):
        """获取有效的访问令牌"""
        if self._is_token_valid():
            return self.token_data['access_token']
        
        return self.refresh_token()

    def _is_token_valid(self):
        """检查令牌是否有效"""
        if not self.token_data:
            return False
        
        # 检查令牌是否存在且未过期
        if 'access_token' not in self.token_data or 'expires_at' not in self.token_data:
            return False
        
        # 检查是否过期（提前5分钟刷新）
        expires_at = datetime.fromtimestamp(self.token_data['expires_at'])
        return datetime.now() < expires_at - timedelta(minutes=5)

    def refresh_token(self):
        """刷新访问令牌"""
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
        }
        
        data = {
            'grant_type': 'client_credentials',
            'scope': ' '.join(self.scopes)
        }
        
        try:
            print(f"正在请求令牌，使用URL: {self.oauth_url}")
            response = requests.post(
                self.oauth_url,
                headers=headers,
                data=data,
                auth=(self.client_id, self.client_secret)
            )
            
            if response.status_code == 200:
                token_data = response.json()
                # 添加过期时间戳
                token_data['expires_at'] = int(time.time()) + token_data['expires_in']
                self._save_token(token_data)
                return token_data['access_token']
            else:
                print(f"Error refreshing token: {response.status_code} - {response.text}")
                return None
                
        except Exception as e:
            print(f"Exception while refreshing token: {e}")
            return None

    def get_token_info(self):
        """获取令牌信息"""
        if not self.token_data:
            return {
                'status': 'No token available',
                'expires_at': None,
                'scopes': [],
                'environment': 'Sandbox' if getattr(settings, 'EBAY_SANDBOX', True) else 'Production'
            }
        
        return {
            'status': 'Valid' if self._is_token_valid() else 'Expired',
            'expires_at': datetime.fromtimestamp(self.token_data['expires_at']).strftime('%Y-%m-%d %H:%M:%S'),
            'scopes': self.token_data.get('scope', '').split(),
            'environment': 'Sandbox' if getattr(settings, 'EBAY_SANDBOX', True) else 'Production'
        } 